/*
 * Copyright 2007-2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.paoding.rose.web.impl.thread;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.paoding.rose.Rc;
import net.paoding.rose.RoseConstants;
import net.paoding.rose.web.impl.module.Module;
import net.paoding.rose.web.var.PrivateVar;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 
 * @author qieqie.wang@paoding.net
 * 
 */
public class ModuleInvocation implements WebInvocation, Comparable<ModuleInvocation> {

	private static Log logger = LogFactory.getLog(Module.class);

	private Module module;

	public ModuleInvocation(Module module) {
		this.module = module;
		init();
	}
	
	private ArrayList<ControllerPathMapping> pathMappings = new ArrayList<ControllerPathMapping>();
	
	protected void init() {
		for (String path : module.getControllerPaths()) {
			Object controller = module.getController(path);
			Class<?> controllerClass = module.getControllerClass(path);
			ControllerInvocation controllerInvocation = new ControllerInvocation(module, path,
					controller, controllerClass);
			ControllerPathMapping pathMapping = new ControllerPathMapping(path, controllerInvocation);
			pathMappings.add(pathMapping);
		}
		Collections.sort(pathMappings);
	}

	public Module getModule() {
		return module;
	}


	@Override
	public Object invoke(HttpServletRequest request, HttpServletResponse response) throws Throwable {
		Path path = PrivateVar.invocationVariables().getPath();
		ControllerInvocation controllerInvocation = getControllerInvocation(path);
		if (controllerInvocation == null) {
			String defControllerPath = module.getDefaultControllerPath();
			if (defControllerPath != null && !defControllerPath.equals(path.getController())) {
				path.injectDefaultControllerPath(defControllerPath);
				if (logger.isDebugEnabled()) {
					logger.debug("translate to Path[" + path + "]");
				}
				controllerInvocation = getControllerInvocation(path);
			}
		}
		if (controllerInvocation == null) {
			if (module.getPath().length() == 0) {
				return RoseConstants.CONTINUE;
			} else {
				return "error:404;[" + module.getPath() + "] not found controller for path "
						+ path.getController() + " when " + request.getMethod() + " "
						+ path.getUri();
			}
		} else {
			Rc.model().add("ctxpath", path.getCtx());
			PrivateVar.invocationVariables().setModuleInvocation(this);
			PrivateVar.invocationVariables().setControllerInvocation(controllerInvocation);
			//
			return invokeController(request, response, controllerInvocation);
		}
	}
	
	protected ControllerInvocation getControllerInvocation(Path path)
		throws IOException {
		MatchResult matchResult = null;
		for (ControllerPathMapping pathMapping : pathMappings) {
			if (logger.isDebugEnabled()) {
				logger.debug("matching: " + pathMapping);
			}
			matchResult = pathMapping.match(path.getControllerInfo());
			if (matchResult != null) {
				if (logger.isDebugEnabled()) {
					logger.debug("matched: " + pathMapping);
					logger.debug("matchResult.matchedString= " + matchResult.getMatchedString());
				}
				if (!path.getController().equals(matchResult.getMatchedString())){
					path.setControllerPath(matchResult.getMatchedString());
					if (logger.isDebugEnabled()) {
						logger.debug("translate to Path [" + path + "]");
					}
				}
				for (String matchResultParam : matchResult.getParameterNames()) {
					Rc.model().add(matchResultParam, matchResult.getParameter(matchResultParam));
				}
				PrivateVar.invocationVariables().setControllerMatchResult(matchResult);
				return pathMapping.getInvocation();
			}
		}
		return null;
	}

	/**
	 * 
	 * @param request
	 * @param response
	 * @param controllerInvocation
	 * @return
	 * @throws Throwable
	 */
	protected Object invokeController(HttpServletRequest request, HttpServletResponse response,
			ControllerInvocation controllerInvocation) throws Throwable {
		return controllerInvocation.invoke(request, response);
	}

	@Override
	public int compareTo(ModuleInvocation o) {
		return this.module.compareTo(o.getModule());
	}

}
